package com.caifu.controller.wardRound;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.controller.AbstractController;
import com.caifu.enums.LabelTypeEnum;
import com.caifu.pojo.*;
import com.caifu.service.ElderlyInfoService;
import com.caifu.service.IHealthArchiveService;
import com.caifu.service.WardRoundService;
import com.caifu.util.Constance;
import com.caifu.util.Util;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther: Lyf
 * @Date: 2020/11/18 13:31
 * @Description:
 */
@Controller
@RequestMapping("/wardRound")
public class WardRoundController extends AbstractController {

    @Autowired
    private ElderlyInfoService elderlyInfoService;

    @Autowired
    private IHealthArchiveService healthArchiveService;

    @Autowired
    private WardRoundService wardRoundService;

    @Autowired
    private TemplateEngine templateEngine;

    /**
     * 功能描述: 列表
     *
     * @auther: Lyf
     * @date: 2020/11/18 15:51
     * @param:
     * @return:
     */
    @GetMapping("/index")
    public String index(ModelMap map) {
        try {
            //楼苑列表
            map.put("buildingList", elderlyInfoService.getBuildingListByPensionNo(getUser().getCurrentPensionNo()));
            //页面需要的数据
            map.put("pageData", elderlyInfoService.getAddPageOfElderlyInfoData());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "wardRound/index";
    }

    /**
     * 功能描述: 查房记录列表
     *
     * @auther: Lyf
     * @date: 2020/11/24 16:25
     * @param:
     * @return:
     */
    @GetMapping("recordList")
    public String recordList(ModelMap map) {
        try {
            map.put("buildingList", elderlyInfoService.getBuildingListByPensionNo(getUser().getCurrentPensionNo()));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "wardRound/record";
    }


    /**
     *
     * 功能描述：查房第一步
     *
     * @Author  Lyf
     * @Date   2020/11/18 15:51
     */
    @RequestMapping("wardRound_one")
    public String wardRound_one(String userNo, Model model){
        try {
            JSONObject userInfo = healthArchiveService.queryElderlyUserInfo(userNo);
            model.addAttribute("userInfo",userInfo);
            model.addAttribute("userNo",userNo);
            model.addAttribute("nations",
                    elderlyInfoService.getYsLabelListByParentCode(LabelTypeEnum.MZ.getKey()));
            model.addAttribute("educations",
                    elderlyInfoService.getYsLabelListByParentCode(LabelTypeEnum.WHCD.getKey()));
            model.addAttribute("marriages",
                    elderlyInfoService.getYsLabelListByParentCode(LabelTypeEnum.HYQK.getKey()));
            //查询健康档案信息
            YlHealthyArchives archives = healthArchiveService.queryHealthyArchivesByUserNo(userNo);
            if(null==archives){
                archives = new YlHealthyArchives();
                archives.setInNo(Constance.disponseDate(Constance
                        .Null2EmptyTrim(userInfo.getString("inDate"))));
                archives.setNation(userInfo.get("nation").toString());
                archives.setAddress(userInfo.get("userAddress").toString());
                archives.setSex(userInfo.get("sex").toString());
                archives.setWorkPlace(userInfo.get("workPlace").toString());
                archives.setJob(userInfo.get("occupation").toString());
                archives.setInDate(userInfo.get("inDate").toString());
            }
            model.addAttribute("archives",archives);
            //查询个人史
            YlUserHistory userHistory = healthArchiveService.queryUserHistoryInfo(userNo);
            if(null==userHistory){
                userHistory = new YlUserHistory();
                userHistory.setEducation(userInfo.get("eductionCode").toString());
            }
            model.addAttribute("userHistory", userHistory);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "wardRound/wardRound_one";
    }


    /**
     *
     * 功能描述：查房第二步
     *
     * @Author  Lyf
     * @Date   2020/11/18 15:51
     */
    @RequestMapping("wardRound_two")
    public String wardRound_two(String batchNo,String userNo, Model model){
        try {
            JSONObject userInfo = healthArchiveService.queryElderlyUserInfo(userNo);
            model.addAttribute("userInfo",userInfo);
            //查询体格价检查信息
            YlPhysiqueCheck checkInfo = healthArchiveService.queryUserPhysiqueCheckByUserNo(userNo);
            model.addAttribute("checkInfo",checkInfo);
            model.addAttribute("userNo",userNo);
            model.addAttribute("batchNo",batchNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "wardRound/wardRound_two";
    }

    /**
     *
     * 功能描述：查房第三步
     *
     * @Author  Lyf
     * @Date   2020/11/18 15:51
     */
    @RequestMapping("wardRound_three")
    public String wardRound_three(String batchNo,String userNo, Model model){
        try {
            SysUser user = getUser();
            JSONObject userInfo = healthArchiveService.queryElderlyUserInfo(userNo);
            model.addAttribute("userInfo",userInfo);
            model.addAttribute("checkInfo",wardRoundService.getCheckInfoList("201",user.getCurrentPensionNo()));
            model.addAttribute("userNo",userNo);
            model.addAttribute("batchNo",batchNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "wardRound/wardRound_three";
    }

    /**
     *
     * 功能描述：查房第四步
     *
     * @Author  Lyf
     * @Date   2020/11/18 15:51
     */
    @RequestMapping("wardRound_four")
    public String wardRound_four(String batchNo,String userNo, Model model){
        try {
            SysUser user = getUser();
            JSONObject userInfo = healthArchiveService.queryElderlyUserInfo(userNo);
            YlPreliminaryDiagnosis pd = wardRoundService.getPreliminaryDiagnosis(batchNo);
            if(pd != null){
                model.addAttribute("checkInfo_select",wardRoundService.getCheckInfoList(pd.getDisease()));
            }
            model.addAttribute("preliminaryDiagnosis",pd);
            model.addAttribute("checkInfo",wardRoundService.getCheckInfoList("202",user.getCurrentPensionNo()));
            model.addAttribute("userInfo",userInfo);
            model.addAttribute("userNo",userNo);
            model.addAttribute("batchNo",batchNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "wardRound/wardRound_four";
    }

    /**
     *
     * 功能描述：查房第五步
     *
     * @Author  Lyf
     * @Date   2020/11/18 15:51
     */
    @RequestMapping("wardRound_five")
    public String wardRound_five(String batchNo,String userNo, Model model){
        try {
            SysUser user = getUser();
            JSONObject userInfo = healthArchiveService.queryElderlyUserInfo(userNo);
            YlPreliminaryDiagnosis pd = wardRoundService.getPreliminaryDiagnosis(batchNo);
            model.addAttribute("preliminaryDiagnosis",pd);
            model.addAttribute("checkInfo",wardRoundService.getCheckInfoList("203",user.getCurrentPensionNo()));
            model.addAttribute("userInfo",userInfo);
            model.addAttribute("userNo",userNo);
            model.addAttribute("batchNo",batchNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "wardRound/wardRound_five";
    }

    /**
     *
     * 功能描述：保存健康档案信息
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("saveBaseHealthyInfo")
    @ResponseBody
    public JSONObject saveBaseHealthyInfo(YlHealthyArchivesRecord healthyArchives
            , YlUserHistoryRecord history){
        SysUser sysUser =getUser();
        try {
            YlWardRoundRecord wardRound = new YlWardRoundRecord();
            wardRound.setCreateTime(new Date());
            wardRound.setCreateBy(sysUser.getUserNo());
            wardRound.setId(Util.getUuid());
            wardRound.setStatus("1");
            wardRound.setUserNo(healthyArchives.getUserNo());

            return wardRoundService.saveBasicHealthyInfo(wardRound,healthyArchives
                    ,history,sysUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * 功能描述：保存体格检查记录
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("savePhysiqueCheckInfo")
    @ResponseBody
    public JSONObject savePhysiqueCheckInfo(YlPhysiqueCheckRecord physiqueCheck){
        SysUser user =getUser();
        try {
            return wardRoundService.savePhysiqueCheckInfo(physiqueCheck,user);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     *
     * 功能描述：保存实验室检查记录
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("saveLaboratoryRecord")
    @ResponseBody
    public Result saveLaboratoryRecord(String data, String batchNo){
        try {
            wardRoundService.saveLaboratoryRecord(data,batchNo);
            return new Result(200,"保存成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"保存失败！");
        }
    }

    /**
     *
     * 功能描述：获取实验室检查记录
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("getLaboratoryRecord")
    @ResponseBody
    public Result getLaboratoryRecord(String batchNo){
        try {
            return new Result(200,"获取数据成功！", wardRoundService.getLaboratoryRecord(batchNo));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }

    /**
     *
     * 功能描述：保存初步检查
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("savePreliminaryInspection")
    @ResponseBody
    public Result savePreliminaryInspection(String batchNo,String data,String text){
        try {
            YlPreliminaryDiagnosis pd = new YlPreliminaryDiagnosis();
            pd.setBatchNo(batchNo);
            pd.setDisease(data);
            pd.setDiseaseText(text);
            wardRoundService.savePreliminaryInspection(pd);
            return new Result(200,"保存成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"保存失败！");
        }
    }

    /**
     *
     * 功能描述：保存诊疗计划
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("saveTreatmentPlan")
    @ResponseBody
    public Result saveTreatmentPlan(String batchNo,String text,String userNo){
        try {
            YlPreliminaryDiagnosis pd = wardRoundService.getPreliminaryDiagnosis(batchNo);
            pd.setTreatmentPlanning(text);
            wardRoundService.editPreliminaryInspection(pd,userNo);
            return new Result(200,"保存成功！",null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"保存失败！");
        }
    }


    /**
     *
     * 功能描述：保存诊疗计划
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("getRecordList")
    @ResponseBody
    public Result getRecordList(int page,int pageSize,String buildingNo,String startDate,String endDate,String userName){
        try {
            int start = (page - 1) * pageSize;
            if(StringUtils.isNotBlank(startDate)){startDate = startDate.replace("-","");}
            if(StringUtils.isNotBlank(endDate)){endDate = endDate.replace("-","");}
            List<Map<String,String>> list = wardRoundService.getList(start,pageSize,buildingNo,startDate,endDate,userName);
            int count = wardRoundService.getListCount(buildingNo,startDate,endDate,userName);
            return new Result(0,"获取数据成功！",count,list);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"获取数据失败！");
        }
    }


    /**
     *
     * 功能描述：获取pdf信息
     *
     * @Author  Lyf
     * @Date   2020/11/12 14:34
     */
    @RequestMapping("getPdfInfo")
    @ResponseBody
    public Result getPdfInfo(String batchNo,String userNo){
        try {
            Map<String,Object> result = new HashMap<>();
            YlWardRoundRecord wr = wardRoundService.getById(batchNo);
            String date = Util.dateToString(wr.getCreateTime(),"yyyy-MM-dd");
            String[] arr = date.split("-");
            result.put("year",arr[0]);
            result.put("month",arr[1]);
            result.put("day",arr[2]);
            String title = "查房报告";
            Map<String,String> userInfo = wardRoundService.getUserInfo(userNo);
            Map<String,String> inspectInfo = wardRoundService.getInspectInfo(batchNo);
            Object obj = null;
            if(userInfo != null && userInfo.size() > 0){
                obj = userInfo.get("birth_date");
                if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                    userInfo.put("birth_date",Util.stringDateToStringDate(String.valueOf(obj),"yyyyMMdd","yyyy年MM月dd日"));
                }

                obj = userInfo.get("org_name");
                if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                    title = String.valueOf(obj)+title;
                }
            }
            result.put("title",title);
            if(inspectInfo != null && inspectInfo.size() > 0){
                obj = inspectInfo.get("sex");
                if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                    String sex = String.valueOf(obj);
                    if("1".equals(sex)){
                        inspectInfo.put("sex","男");
                    }else if("2".equals(sex)){
                        inspectInfo.put("sex","女");
                    }else{
                        inspectInfo.put("sex","不详");
                    }
                }
                obj = inspectInfo.get("disease");
                List<YlCheckInfo> list = new ArrayList<>();
                if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                    list = wardRoundService.getCheckInfoList(String.valueOf(obj));
                }
                obj = inspectInfo.get("disease_text");
                if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                   YlCheckInfo checkInfo = new YlCheckInfo();
                   checkInfo.setCheckName(String.valueOf(obj));
                   list.add(checkInfo);
                }
                obj = inspectInfo.get("treatment_planning");
                if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                    String[] tpArr = String.valueOf(obj).split("\n");
                    boolean flag = true;
                    if(tpArr != null && tpArr.length > 0){
                        if(StringUtils.isBlank(tpArr[tpArr.length - 1])){
                            flag = false;
                            result.put("treatmentPlanning",Arrays.copyOf(tpArr, tpArr.length-1));
                        }
                    }
                    if(flag) {
                        result.put("treatmentPlanning", tpArr);
                    }
                }else{
                    result.put("treatmentPlanning",null);
                }
                result.put("disease",list);
            }else{
                result.put("disease",null);
                result.put("treatmentPlanning",null);
            }
            result.put("userInfo",userInfo);
            result.put("inspectInfo",inspectInfo);
            result.put("laboratory",wardRoundService.getLaboratoryRecord_two(batchNo));

            return new Result(200,"保存成功！",result);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1,"保存失败！");
        }
    }


    @RequestMapping(value = "createPdf")
    public void createPdf(String userNo,String batchNo, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //设置字符 否则pdf不会显示中文
        String fontStyle = "templates/wardRound/simSun.ttf";
        //模板文件
        String pdfTemplate = "wardRound/pdf_template";
        //获取路径 设置成了全路径，要不然在pdf中不显示
        String baseUrl = request.getRequestURL().substring(0, StringUtils.ordinalIndexOf(request.getRequestURL(), "/", 4));
        //设置PDF参数
        WebContext ctx = new WebContext(request, response, request.getServletContext(), request.getLocale());

        YlWardRoundRecord wr = wardRoundService.getById(batchNo);
        String date = Util.dateToString(wr.getCreateTime(),"yyyy-MM-dd");
         String[] arr = date.split("-");
        String title = "查房报告";
        Map<String,String> userInfo = wardRoundService.getUserInfo(userNo);
        Map<String,String> inspectInfo = wardRoundService.getInspectInfo(batchNo);
        Object obj = null;
        if(userInfo != null && userInfo.size() > 0){
            obj = userInfo.get("birth_date");
            if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                userInfo.put("birth_date",Util.stringDateToStringDate(String.valueOf(obj),"yyyyMMdd","yyyy年MM月dd日"));
            }

            obj = userInfo.get("org_name");
            if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                title = String.valueOf(obj)+title;
            }
        }

        if(inspectInfo != null && inspectInfo.size() > 0){
            obj = inspectInfo.get("sex");
            if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                String sex = String.valueOf(obj);
                if("1".equals(sex)){
                    inspectInfo.put("sex","男");
                }else if("2".equals(sex)){
                    inspectInfo.put("sex","女");
                }else{
                    inspectInfo.put("sex","不详");
                }
            }
            obj = inspectInfo.get("disease");
            List<YlCheckInfo> list = new ArrayList<>();
            if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                list = wardRoundService.getCheckInfoList(String.valueOf(obj));
            }
            obj = inspectInfo.get("disease_text");
            if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                YlCheckInfo checkInfo = new YlCheckInfo();
                checkInfo.setCheckName(String.valueOf(obj));
                list.add(checkInfo);
            }
            obj = inspectInfo.get("treatment_planning");
            if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))) {
                ctx.setVariable("treatmentPlanning",String.valueOf(obj).split("\n"));
            }else{
                ctx.setVariable("treatmentPlanning",null);
            }
            ctx.setVariable("disease",list);
        }else{
            ctx.setVariable("disease",null);
            ctx.setVariable("treatmentPlanning",null);
        }
        ctx.setVariable("userInfo",userInfo);
        ctx.setVariable("inspectInfo", inspectInfo);
        ctx.setVariable("laboratory",wardRoundService.getLaboratoryRecord_two(batchNo));
        ctx.setVariable("year", arr[0]);
        ctx.setVariable("month",arr[1]);
        ctx.setVariable("day",arr[2]);
        ctx.setVariable("title",title);
        ctx.setVariable("baseUrl", baseUrl);
        try {
            //  为模板文件，注意路径和“/”
            String htmlContext = templateEngine.process(pdfTemplate, ctx);
            // 测试用 downloadPdf(htmlContext, "C:\\Users\\hml\\Desktop\\" + Constance.randNumber(10) + ".pdf", fontStr,response);
            downloadPdf(htmlContext, Constance.randNumber(10) + ".pdf", fontStyle, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void downloadPdf(String content, String pdfName, String fontStyle, HttpServletResponse response) throws DocumentException, IOException {
        // response 响应参数设置
        response.setContentType("application/pdf;charset=utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(pdfName, "UTF8"));
        response.setHeader("FileName", URLEncoder.encode(pdfName, "UTF8"));
        ServletOutputStream servletOutputStream = response.getOutputStream();

        ITextRenderer renderer = new ITextRenderer();

        ITextFontResolver fontResolver = renderer.getFontResolver();
        try {
            //设置字体，否则不支持中文,在html中使用字体，html{ font-family: SimSun;}
            fontResolver.addFont(fontStyle, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        renderer.setDocumentFromString(content);
        renderer.layout();
        //测试用 renderer.createPDF(new FileOutputStream(new File(pdfName)));
        renderer.createPDF(servletOutputStream);
        servletOutputStream.flush();
        servletOutputStream.close();
    }
}
